package com.ylsk.check.service.impl;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONObject;
import com.ylsk.check.domain.dto.MsgTemplateDTO;
import com.ylsk.check.domain.dto.ReportInfoDTO;
import com.ylsk.check.domain.dto.SendMsgArgsDTO;
import com.ylsk.check.domain.emum.ConstructionStatusEnum;
import com.ylsk.check.domain.emum.MsgTemplateEnum;
import com.ylsk.check.domain.emum.ReportStatusEnum;
import com.ylsk.check.domain.so.ReportInfoSO;
import com.ylsk.check.domain.vo.ReportInfoVO;
import com.ylsk.check.util.SendMsg;
import com.ylsk.common.annotation.DataScope;
import com.ylsk.common.config.SnowIdConfig;
import com.ylsk.common.core.domain.entity.SysUser;
import com.ylsk.common.exception.ServiceException;
import com.ylsk.common.utils.DateUtils;
import com.ylsk.common.utils.SecurityUtils;
import com.ylsk.common.utils.SerialNoUtils;
import com.ylsk.common.utils.StringUtils;
import com.ylsk.system.helper.FileHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ylsk.check.mapper.ReportInfoMapper;
import com.ylsk.check.domain.ReportInfo;
import com.ylsk.check.service.IReportInfoService;
import org.springframework.transaction.annotation.Transactional;


/**
 * 报备信息Service业务层处理
 *
 * @author yangsy
 * @date 2023-12-13
 */
@Service
public class ReportInfoServiceImpl implements IReportInfoService
{
    private static final Logger log = LoggerFactory.getLogger(ReportInfoServiceImpl.class);
    @Autowired
    private ReportInfoMapper reportInfoMapper;

    @Autowired
    private SnowIdConfig snowIdConfig;

    @Autowired
    private SerialNoUtils serialNoUtils;

    @Autowired
    private FileHelper fileHelper;

    @Autowired
    private ReportInfoHelper helper;

    /**
     * 查询报备信息
     *
     * @param reportInfoId 报备信息主键
     * @return 报备信息
     */
    @Override
    public ReportInfoVO selectreportInfoByreportInfoId(Long reportInfoId)
    {
        if(null == reportInfoId){
            throw new ServiceException("reportInfoId is null");
        }
        ReportInfoVO reportInfoVO = reportInfoMapper.selectreportInfoByreportInfoId(reportInfoId);
        //  封装附件内容数据
        Long organizationFileId = reportInfoVO.getOrganizationFileId();
        if(null != organizationFileId){
            reportInfoVO.setOrganizationFile(fileHelper.getFileByBusinessId(organizationFileId));
        }
        Long licenseFileId = reportInfoVO.getLicenseFileId();
        if(null != licenseFileId){
            reportInfoVO.setLicenseFile(fileHelper.getFileByBusinessId(licenseFileId));
        }
        Long trafficFileId = reportInfoVO.getTrafficFileId();
        if(null != trafficFileId){
            reportInfoVO.setTrafficFile(fileHelper.getFileByBusinessId(trafficFileId));
        }
        Long emergencyPlanFileId = reportInfoVO.getEmergencyPlanFileId();
        if(null != emergencyPlanFileId){
            reportInfoVO.setEmergencyPlanFile(fileHelper.getFileByBusinessId(emergencyPlanFileId));
        }
        Long safetyTrainingFileId = reportInfoVO.getSafetyTrainingFileId();
        if(null != safetyTrainingFileId){
            reportInfoVO.setSafetyTrainingFile(fileHelper.getFileByBusinessId(safetyTrainingFileId));
        }
        Long qualificationCertificationFileId = reportInfoVO.getQualificationCertificationFileId();
        if(null != qualificationCertificationFileId){
            reportInfoVO.setQualificationCertificationFile(fileHelper.getFileByBusinessId(qualificationCertificationFileId));
        }
        Long otherFileId = reportInfoVO.getOtherFileId();
        if(null != otherFileId){
            reportInfoVO.setOtherFile(fileHelper.getFileByBusinessId(otherFileId));
        }
        return reportInfoVO;
    }

    /**
     * 查询报备信息列表
     *
     * @param reportInfoSO 报备信息
     * @return 报备信息
     */
    @Override
    @DataScope(deptAlias = "te",userAlias = "tf")
    public List<ReportInfoVO> selectreportInfoList(ReportInfoSO reportInfoSO)
    {
        //做个判断  因为施工端和执法端 用的同一个接口 这个地方需要做个特殊处理 执法端只需要查看已提交的数据
        reportInfoSO.setUserType(SecurityUtils.getUserType());
        reportInfoSO.setOperateUserId(SecurityUtils.getUserId());
        return reportInfoMapper.selectreportInfoList(reportInfoSO);
    }

    /**
     * 新增报备信息
     *
     * @param reportInfoDTO 报备信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertreportInfo(ReportInfoDTO reportInfoDTO)
    {
        Integer reportStatus = reportInfoDTO.getReportStatus();
        if(null == reportStatus){
            throw new ServiceException("报备状态不能为空!");
        }
        final Long reportInfoId = snowIdConfig.getSnowId();
        //  施工组织方案 附件
        final Long organizationFileId = snowIdConfig.getSnowId();
        //  施工许可文件 附件
        final Long licenseFileId = snowIdConfig.getSnowId();
        //  交通组织方案 附件
        final Long trafficFileId = snowIdConfig.getSnowId();
        //   应急预案 附件
        final Long emergencyPlanFileId = snowIdConfig.getSnowId();
        //  安全培训材料 附件
        final Long safetyTrainingFileId = snowIdConfig.getSnowId();
        //  资质证明材料 附件
        final Long qualificationCertificationFileId = snowIdConfig.getSnowId();
        //  其他材料 附件
        final Long otherFileId = snowIdConfig.getSnowId();

        ReportInfo reportInfo = new ReportInfo();
        BeanUtils.copyProperties(reportInfoDTO,reportInfo);
        reportInfo.setReportInfoId(reportInfoId);
        //自动生成流水号
        reportInfo.setReportNum(serialNoUtils.generateSerialNo(SerialNoUtils.SGBB_ORDER));

        reportInfo.setOrganizationFileId(organizationFileId);
        reportInfo.setLicenseFileId(licenseFileId);
        reportInfo.setTrafficFileId(trafficFileId);
        reportInfo.setEmergencyPlanFileId(emergencyPlanFileId);
        reportInfo.setSafetyTrainingFileId(safetyTrainingFileId);
        reportInfo.setQualificationCertificationFileId(qualificationCertificationFileId);
        reportInfo.setOtherFileId(otherFileId);

        //审核人  根据部门id 获取相应的施工管理员数据
        Long deptId = reportInfoDTO.getDeptId();
        if(null == deptId){
            throw new ServiceException("归属管辖大队不能为空!");
        }
        SysUser sysUser = helper.getDeptDataManager(deptId);
        if(null == sysUser){
            throw new ServiceException("未找到当前管辖大队,施工管理员");
        }
        //  取第一个人 作为审核人
        reportInfo.setReviewedBy(sysUser.getUserId());

        int result = 0 ;
        //   organizationFile
        String organizationFile = reportInfoDTO.getOrganizationFile();
        if(StringUtils.isNotEmpty(organizationFile)){
            result += fileHelper.saveBusinessFileData(organizationFile,organizationFileId);
        }
        //  licenseFile
        String licenseFile = reportInfoDTO.getLicenseFile();
        if(StringUtils.isNotEmpty(licenseFile)){
            result += fileHelper.saveBusinessFileData(licenseFile,licenseFileId);
        }
        //  trafficFile
        String trafficFile = reportInfoDTO.getTrafficFile();
        if(StringUtils.isNotEmpty(trafficFile)){
            result += fileHelper.saveBusinessFileData(trafficFile,trafficFileId);
        }
        //  emergencyPlanFile
        String emergencyPlanFile = reportInfoDTO.getEmergencyPlanFile();
        if(StringUtils.isNotEmpty(emergencyPlanFile)){
            result += fileHelper.saveBusinessFileData(emergencyPlanFile,emergencyPlanFileId);
        }
        //  safetyTrainingFile
        String safetyTrainingFile = reportInfoDTO.getSafetyTrainingFile();
        if(StringUtils.isNotEmpty(safetyTrainingFile)){
            result += fileHelper.saveBusinessFileData(safetyTrainingFile,safetyTrainingFileId);
        }
        //  qualificationCertificationFile
        String qualificationCertificationFile = reportInfoDTO.getQualificationCertificationFile();
        if(StringUtils.isNotEmpty(qualificationCertificationFile)){
            result += fileHelper.saveBusinessFileData(qualificationCertificationFile,qualificationCertificationFileId);
        }
        //  otherFile
        String otherFile = reportInfoDTO.getOtherFile();
        if(StringUtils.isNotEmpty(otherFile)){
            result += fileHelper.saveBusinessFileData(otherFile,otherFileId);
        }
        //设置备案时间 为提交时间
        reportInfo.setFilingDate(new Date());
        result += reportInfoMapper.insert(reportInfo);

        //  用户直接提交操作 需要写入消息表
        if(reportInfoDTO.getReportStatus() == ReportStatusEnum.SUBMIT.getCode()){
            //  提交操作  消息 需要发送给施工管理员 和 分管领导
            List<Long> toUser = helper.getDeptLeader(deptId).stream().map(SysUser::getUserId).collect(Collectors.toList());
            MsgTemplateDTO msgTemplateDTO = new MsgTemplateDTO(MsgTemplateEnum.TEMPLATE_SGBB,SecurityUtils.getUserId(),toUser);
            String p1 = SecurityUtils.getLoginUser().getUser().getNickName();
            String p2 = DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss");
            String p3 = reportInfo.getProjectName();
            helper.saveMsg(msgTemplateDTO,p1, p2,p3);

            //  提交操作  需要发送短信给施工管理员 和 分管领导
            //发送短信息
            for (int i = 0; i < toUser.size(); i++) {
                SysUser user = helper.getUserInfo(toUser.get(i));
                SendMsgArgsDTO sendMsgArgsDTO = new SendMsgArgsDTO();
                sendMsgArgsDTO.setTellPhone(user.getPhonenumber());
                sendMsgArgsDTO.setProject(SendMsgArgsDTO.PROEJCT_SGBB);
                JSONObject vars = new JSONObject();
                vars.put("project",p3);
                sendMsgArgsDTO.setVars(vars);
                log.info("发送人员电话号码={},所属大队={},参数内容={}", user.getPhonenumber(),user.getDept().getDeptName(),vars.toString());
                SendMsg.toSend(helper.enableSendMsg(),sendMsgArgsDTO);
            }
        }

        //施工状态   新增操作 默认设置为未进场
        helper.updateReportConstructionStatus(reportInfo,ConstructionStatusEnum.NOT_ENTERY);
        return result;
    }

    /**
     * 修改报备信息
     *
     * @param reportInfoDTO 报备信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updatereportInfo(ReportInfoDTO reportInfoDTO)
    {
        final Long reportInfoId = reportInfoDTO.getReportInfoId();
        if(null == reportInfoId){
            throw new ServiceException("reportInfoId is null");
        }
        ReportInfo reportInfo = new ReportInfo();
        BeanUtils.copyProperties(reportInfoDTO,reportInfo);
        ReportInfo _reportInfo = helper.getReportInfo(reportInfoId);
        //审核人  根据部门id 获取相应的施工管理员数据
        Long deptId = reportInfoDTO.getDeptId();
        if(null == deptId){
            throw new ServiceException("归属管辖大队不能为空!");
        }
        SysUser sysUser = helper.getDeptDataManager(deptId);
        if(null == sysUser){
            throw new ServiceException("未找到当前管辖大队,施工管理员");
        }
        //  取第一个人 作为审核人
        reportInfo.setReviewedBy(sysUser.getUserId());
        int  result = 0 ;

        String organizationFile = reportInfoDTO.getOrganizationFile();
        result += fileHelper.updateBusinessFileData(organizationFile,_reportInfo.getOrganizationFileId());

        String licenseFile = reportInfoDTO.getLicenseFile();
        result += fileHelper.updateBusinessFileData(licenseFile,_reportInfo.getLicenseFileId());

        String trafficFile = reportInfoDTO.getTrafficFile();
        result += fileHelper.updateBusinessFileData(trafficFile,_reportInfo.getTrafficFileId());


        String emergencyPlanFile = reportInfoDTO.getEmergencyPlanFile();
        result += fileHelper.updateBusinessFileData(emergencyPlanFile,_reportInfo.getEmergencyPlanFileId());

        String safetyTrainingFile = reportInfoDTO.getSafetyTrainingFile();
        result += fileHelper.updateBusinessFileData(safetyTrainingFile,_reportInfo.getSafetyTrainingFileId());


        String qualificationCertificationFile = reportInfoDTO.getQualificationCertificationFile();
        result += fileHelper.updateBusinessFileData(qualificationCertificationFile,_reportInfo.getQualificationCertificationFileId());


        String otherFile = reportInfoDTO.getOtherFile();
        result += fileHelper.updateBusinessFileData(otherFile,_reportInfo.getOtherFileId());
        //  用户直接提交操作 需要写入消息表
        if(reportInfoDTO.getReportStatus() == ReportStatusEnum.SUBMIT.getCode()){
            //  提交消息 需要发送给施工管理员 和 分管领导
            List<Long> toUser = helper.getDeptLeader(_reportInfo.getDeptId()).stream().map(SysUser::getUserId).collect(Collectors.toList());
            MsgTemplateDTO msgTemplateDTO = new MsgTemplateDTO(MsgTemplateEnum.TEMPLATE_SGBB,SecurityUtils.getUserId(),toUser);
            String p1 = SecurityUtils.getLoginUser().getUser().getNickName();
            String p2 = DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss");
            String p3 = reportInfo.getProjectName();
            helper.saveMsg(msgTemplateDTO,p1, p2,p3);

            //发送短信息
            for (int i = 0; i < toUser.size(); i++) {
                SysUser user = helper.getUserInfo(toUser.get(i));
                SendMsgArgsDTO sendMsgArgsDTO = new SendMsgArgsDTO();
                sendMsgArgsDTO.setTellPhone(user.getPhonenumber());
                sendMsgArgsDTO.setProject(SendMsgArgsDTO.PROEJCT_SGBB);
                JSONObject vars = new JSONObject();
                vars.put("project",p3);
                sendMsgArgsDTO.setVars(vars);
                log.info("发送人员电话号码={},所属大队={},参数内容={}", user.getPhonenumber(),user.getDept().getDeptName(),vars.toString());
                SendMsg.toSend(helper.enableSendMsg(),sendMsgArgsDTO);
            }
        }
        //更新业务数据
        result += reportInfoMapper.updateById(reportInfo);
        return  result;
    }

    /**
     * 批量删除报备信息
     *
     * @param reportInfoIds 需要删除的报备信息主键
     * @return 结果
     */
    @Override
    public int deletereportInfoByreportInfoIds(Long[] reportInfoIds)
    {
        return reportInfoMapper.deletereportInfoByreportInfoIds(reportInfoIds);
    }

    /**
     * 删除报备信息信息
     *
     * @param reportInfoId 报备信息主键
     * @return 结果
     */
    @Override
    public int deletereportInfoByreportInfoId(Long reportInfoId)
    {
        if(null == reportInfoId){
            throw new ServiceException("项目报备id不能为空!");
        }
        ReportInfo reportInfo = reportInfoMapper.selectById(reportInfoId);
        if(null == reportInfo){
            throw new ServiceException(StringUtils.format(" 项目报备id= {} ,施工内容不存在",reportInfoId));
        }
        if(reportInfo.getReportStatus() != ReportStatusEnum.DRAFT.getCode()){
            throw new ServiceException("当前项目报备状态数据不是草稿,不允许删除!");
        }
        return reportInfoMapper.deletereportInfoByreportInfoId(reportInfoId);
    }
}
